package com.elm.service.impl;

import com.elm.dao.BusinessDao;
import com.elm.dao.OrderDao;
import com.elm.dao.OrderDetailetDao;
import com.elm.entity.Business;
import com.elm.entity.OrderDetailet;
import com.elm.entity.Orders;
import com.elm.service.OrderService;

import java.sql.SQLException;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    private final OrderDao orderDao;
    private final BusinessDao businessDao;
    private final OrderDetailetDao orderDetailetDao;

    public OrderServiceImpl() {
        orderDao = new OrderDao();
        businessDao = new BusinessDao();
        orderDetailetDao = new OrderDetailetDao();
    }
    @Override
    public int doCreateOrders(Orders orders) throws SQLException {
        orders.setOrderDate(String.valueOf(System.currentTimeMillis()));
        return orderDao.createOrders(orders);
    }

    @Override
    public List<Orders> doGetOrdersListByUserId(String userId) throws SQLException{
        List<Orders> ordersList = orderDao.getOrdersListByUserId(userId);
        ordersList = ordersList.stream().map(item -> {
            int businessId = item.getBusinessId();
            Business business = businessDao.getBusinessById(businessId);
            item.setBusiness(business);
            int orderId = item.getOrderId();
            try {
                List<OrderDetailet> list = orderDetailetDao.getListByOrderId(orderId);
                item.setList(list);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return item;
        }).toList();


        return ordersList;
    }

    @Override
    public Orders getOrdersById(String orderId) throws SQLException {
        Orders orders = orderDao.getOrdersById(orderId);
        int businessId = orders.getBusinessId();
        Business business = businessDao.getBusinessById(businessId);
        orders.setBusiness(business);
        List<OrderDetailet> list = orderDetailetDao.getListByOrderId(Integer.parseInt(orderId));
        orders.setList(list);

        return orders;
    }
}